﻿using KseCms.Application.Services;
using KseCms.Core;

namespace KseCms.Application
{
    public class ShoppingCartService : IShoppingCartService, ITransient
    {
        private readonly IRepository<ShoppingCart> _shoppingCartRepository;

        private readonly IRepository<Product> _productRepository;

        public ShoppingCartService(IRepository<ShoppingCart> shoppingCartRepository,
            IRepository<Product> productRepository)
        {
            _shoppingCartRepository = shoppingCartRepository;
            _productRepository = productRepository;
        }

        public async Task<ShoppingCartDto> GetById(string id)
        {
            var entity = await _shoppingCartRepository.DetachedEntities.FirstOrDefaultAsync(n => n.Id == id);

            return entity.Adapt<ShoppingCartDto>();
        }

        public async Task<PagedList<ShoppingCartDto>> GetList(PageDto page)
        {
            var query = from cart in _shoppingCartRepository.AsQueryable(false)
                        join product in _productRepository.AsQueryable(false) on cart.ProductId equals product.Id
                        select new ShoppingCartDto
                        {
                            Id = cart.Id,
                            Quantity = cart.Quantity,
                            Amount = cart.Amount,
                            CreatedDate = cart.CreatedDate,
                            UpdatedDate = cart.UpdatedDate,
                            Product = product.Adapt<ProductDto>(),
                        };

            return await query.ToPagedListAsync(page.PageIndex, page.PageSize);
        }

        public async Task Create(ShoppingCartDto shoppingCart)
        {
            var entity = shoppingCart.Adapt<ShoppingCart>();

            await _shoppingCartRepository.InsertNowAsync(entity);
        }

        public async Task Delete(string id)
        {
            if (!IsExists(id))
                throw Oops.Oh(ErrorCodes.record_not_exist);

            await _shoppingCartRepository.DeleteNowAsync(id);
        }

        public async Task Update(ShoppingCartDto shoppingCart)
        {
            UpdateValidation(shoppingCart);

            var entity = shoppingCart.Adapt<ShoppingCart>();

            await _shoppingCartRepository.UpdateNowAsync(entity);
        }

        private void UpdateValidation(ShoppingCartDto shoppingCart)
        {
            if (!IsExists(shoppingCart.Id))
                throw Oops.Oh(ErrorCodes.record_not_exist);

            //to-do other validate
        }

        private bool IsExists(string id)
        {
            return _shoppingCartRepository.DetachedEntities.Any(u => u.Id == id);
        }
    }
}